package com.ddxz.spark.read.tools


import com.ddxz.spark.read.struct.MySqlEntity.FacilityEntity

import scala.collection.mutable.ArrayBuffer

object CommonTools {
  private[this] val ipv4Regex = """^(([1-9]?[0-9]|1[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.){3}([1-9]?[0-9]|1?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$""".r

  def getHostByUrl(url:String): String ={
    if(url==null || url.trim.length<1){
      ""
    }else{
      var host = url
      if(host.startsWith("www.")){
        host = host.replaceAll("www.","")
      }
      host.toLowerCase()
    }
  }

  def ipToLong(ip: String): Long = {
    if (!ipIsIPV4(ip)) {//非法IP
      -1
    } else {
      val res = ip.trim.replaceAll("(\r|\n)", "")
      val ips = res.split("\\.", -1)
      (ips(0).toLong << 24) + (ips(1).toLong << 16) + (ips(2).toLong << 8) + ips(3).toLong
    }
  }

  def ipToString(ip: Long): String = {
    val sb = new StringBuilder
    if (ip < 1) {//数据为空
      ""
    } else {
      try {
        var tmp = ip
        val arr = ArrayBuffer[Long]()
        for (i <- 1 to 4) {
          val ni = tmp & 0xFF
          arr += ni
          tmp >>= 8
        }

        for (s <- arr.reverse) {
          sb.append(s).append(".")
        }
        sb.deleteCharAt(sb.length - 1)
      } catch {
        case e: Exception => println("IP转换异常:"+e)
      }
      sb.toString
    }
  }

  def parseIpRange(arg:  FacilityEntity): Array[FacilityEntity] = {
    val ipList = ArrayBuffer[FacilityEntity]()
    if(arg.ips != null && arg.ips.trim.length > 6) {
      val ipRangeList = arg.ips.replaceAll("(\r|\n)", "").split(",")
      ipRangeList.foreach(ipRange => {
        val range: (Long, Long) = getIntegerIpRange(ipRange)
        for(ip <- range._1 to range._2) {
          ipList += (FacilityEntity(ipToString(ip), "", arg.facilityId, arg.deptId))
        }
      })
    }

    if(arg.domain != null && arg.domain.trim.length > 0) {
      val domainList = arg.domain.replaceAll("(\r|\n)", "").split(",")
      domainList.foreach(domain => ipList += (FacilityEntity("", domain, arg.facilityId, arg.deptId)))
    }

    ipList.distinct.toArray
  }

  def getIntegerIpRange(str: String): (Long, Long) = {
    var range: (Long, Long) = (0, 0)
    if(str.contains("/")) {
      val startIp = ipToLong(IpCaculate.getStartIp(str))
      val endIp = ipToLong(IpCaculate.getEndIp(str))

      range = (startIp, endIp)
    } else if(str.contains("-")) {
      val ips = str.split("-");
      val startIp = ipToLong(ips(0))
      val endIp = ipToLong(ips(1))

      range = (startIp, endIp)
    } else {
      val ip = ipToLong(str)

      range = (ip, ip)
    }

    range
  }

  def ipIsIPV4(ip: String): Boolean = {
    if (ip == null || !ipv4Regex.findFirstIn(ip.trim).isDefined)
      false
    else
      true
  }
}
